package com.zhang.admin.controller;

import com.zhang.admin.bean.Permission;
import com.zhang.admin.bean.Role;
import com.zhang.admin.bean.RolePermission;
import com.zhang.admin.service.RolePermissionService;
import com.zhang.admin.service.RoleService;
import com.zhang.util.Result;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @title: 角色控制器
 * @author: zhangyf
 * @date: 2023/3/29 14:47
 **/
@RestController
@RequestMapping("/admin/role")
public class RoleController {

    /**
     * 获取所有角色
     * @return
     */
    @GetMapping("getAllRoles")
    public Result<List<Role>> getAllRoles() {
        return Result.of(200,"success", RoleService.getAllRole());
    }

    /**
     * 根据ID删除角色
     * @param roleId
     * @return
     */
    @DeleteMapping("deleteRole/{roleId}")
    public Result<String> deleteRoleById(@PathVariable Long roleId){
        RoleService.deleteRole(roleId);
        return Result.of(200,"success","删除角色成功");
    }

    /**
     * 添加角色
     * @param roleName
     * @return
     */
    @PostMapping("addRole")
    public Result<String> addRole(@RequestBody String roleName){
        RoleService.addRole(roleName);
        return Result.of(200,"success","添加角色成功");
    }

    /**
     * 根据角色id获取菜单
     * @param roleId
     * @return
     */
    @GetMapping("permissions/{roleId}")
    public Result<List<Permission>> getPermissionsByRoleId(@PathVariable Long roleId){
        return Result.of(200,"success", RolePermissionService.getPermissionsByRoleId(roleId));
    }

    /**
     * 为用户分配角色
     * @param rolePermission
     * @return
     */
    @PostMapping("assignPermissionsToRole")
    public Result<String> assignPermissionsToRole(@RequestBody RolePermission rolePermission){
        RolePermissionService.addRolePermissions(
                rolePermission.getRoleId(),
                Arrays.stream(rolePermission.getPermissionIds().split(",")).map(Long::parseLong).collect(Collectors.toList())
        );
        return Result.of(200,"success","分配角色成功");
    }
}
